# coding=utf-8
import random
import re

from flask import current_app
from flask import json, jsonify
from flask import make_response
from flask import request
from flask import session

from info import redis_store, db
from info.libs.yuntongxun.sms import CCP
from info.models import User
from info.utils.captcha.captcha import captcha
from info.utils.response_code import RET
from . import verify_blue
from datetime import datetime


@verify_blue.route('/logout', methods=['POST'])
def logout():
    # 清除session
    session.pop("user_id",None)
    session.pop("nick_name",None)
    session.pop("is_admin", None)
    return jsonify(errno=RET.OK,errmsg="退出登陆成功")


@verify_blue.route('/login', methods=['POST'])
def login():
    #1,获取参数
    mobile = request.json.get("mobile")
    password = request.json.get("password")

    #2,校验参数
    #2,1 根据手机号,获取用户对象,并判断是否存在
    try:
        user = User.query.filter(User.mobile == mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="查询用户失败")

    # 2,2 判断密码是否正确,TODU if not正确校验格式反而一直报错
    if not user.check_passowrd(password):
        return jsonify(errno=RET.DATAERR,errmsg="密码输入错误")

    #3,状态保持(session)
    session["user_id"] = user.id
    session["nick_name"] = user.nick_name
    session["is_admin"] = False

    # last_login最后登陆时间记录
    # try:
    #     user.last_login = datetime.now()
    #     # db.session.commit()
    # except Exception as e:
    #     current_app.logger.error(e)
    user.last_login = datetime.now()

    #4,返回响应
    return jsonify(errno=RET.OK,errmsg="登陆成功")


@verify_blue.route('/register', methods=['POST'])
def register():
    # 1 获取参数 mobile,sms_code,password
    json_data = request.data
    dict_data = json.loads(json_data)
    mobile = dict_data.get("mobile")
    sms_code = dict_data.get("sms_code")
    password = dict_data.get("password")

    # 2 校验参数
    count = User.query.filter_by(mobile=mobile).count()
    if count > 0:
        return jsonify(errno=RET.DATAERR, errmsg="用户已经存在")

    redis_sms_code = redis_store.get("sms_code_id:%s" % mobile)
    if not redis_sms_code:
        return jsonify(errno=RET.DATAERR, errmsg="短信验证码已过期")

    if redis_sms_code != sms_code:
        return jsonify(errno=RET.DATAERR, errmsg="短信验证码输入错误")

    # 3 创建用户,数据入库
    try:
        user = User()
        user.nick_name = mobile
        # 注意：user.password_hash = password （数据库显示明文）和 user.password = password 的区别
        user.password= password
        user.mobile = mobile
        db.session.add(user)
        db.session.commit()

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="注册失败")

    # 4 返回响应
    return jsonify(errno=RET.OK, errmsg="注册成功")


@verify_blue.route('/sms_code',methods=["POST"])
def sms_code():
    # 1 获取参数,mobile, image_code,image_code_id
    # json_data = request.data
    # dict_data = json.loads(json_data)
    dict_data = request.json
    mobile = dict_data.get("mobile")
    image_code = dict_data.get("image_code")
    image_code_id = dict_data.get("image_code_id")

    # 2 校验参数
    if not all([mobile,image_code,image_code_id]):
        return jsonify(errno=RET.DATAERR,errmsg="参数不全")
    # if not all([mobile,image_code,image_code_id]):
    #     return jsonify(errno=RET.PARAMERR, errmsg="参数不全")

    redis_image_code = redis_store.get("image_code:%s"%image_code_id)
    if not redis_image_code:
        return jsonify(errno=RET.DATAERR,errmsg="图片验证码已经过期")

    if redis_image_code.lower() != image_code.lower():
        return jsonify(errno=RET.DATAERR,errmsg="图片验证码填写错误")

    if not re.match("1[3-9]\d{9}",mobile):
        return jsonify(errno=RET.PARAMERR,errmsg="手机格式不正确")

    # 3 发送短信,sms_code数据入库
    sms_code = "%06d"%random.randint(0,999999)
    # ccp = CCP()
    # result = ccp.send_template_sms(mobile, [sms_code, 5], 1)
    # if result == -1:
    #     return jsonify(errno=RET.THIRDERR,errmsg="发送失败")
    print(sms_code)

    redis_store.set("sms_code_id:%s" % mobile,sms_code,300)

    # 4 返回参数
    return jsonify(errno=RET.OK,errmsg="发送成功")


@verify_blue.route('/image_code')
def image_code():
    # 1, 获取参数, cur_id
    cur_id = request.args.get("cur_id")
    pre_id = request.args.get("pre_id")

    # 2, 校验参数
    if not cur_id:
        return "参数不全"

    if pre_id:
        redis_store.delete("image_code:%s"%pre_id)

    # 3, 生成图片验证码
    name, text, image_code = captcha.generate_captcha()
    # 4, 存储到redis中
    redis_store.set("image_code:%s"%cur_id,text,300)

    # 5, 返回图片验证码
    response = make_response(image_code)
    response.headers["Content-Type"] = "image/png"
    return response




